package com.project.contorller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.*;
import com.project.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("stu")
public class StudentController {
    @Autowired
    public IStudentService service;
    @RequestMapping("findAll")
    public IPage<StudentBean> finAll(Integer pageNo, String name, String className, String roomName){
        return service.findItem(pageNo,name,className,roomName);
    }
    @RequestMapping("add")
    public String addStudent(@Valid StudentBean studentBean, Integer chId, Integer roId, BindingResult br) throws JsonProcessingException {
        if (br.hasErrors()){//判断是否有验证失败信息
            //得到校验失败的集合
            List<FieldError> list=br.getFieldErrors();
            //将校验失败集合转换为json字符串发送给客户端
            ObjectMapper om=new ObjectMapper();

            String errorInfo=om.writeValueAsString(list);
            return errorInfo;
        }
        ClassBean classBean=new ClassBean();
        classBean.setId(chId);
        RoomBean roomBean=new RoomBean();
        roomBean.setId(roId);
        studentBean.setClassBean(classBean);
        studentBean.setRoomBean(roomBean);
        service.addStudent(studentBean);
        return "ok";
    }
    @RequestMapping("update")
    public void update(Integer stuId, Integer roomId){
        service.update(stuId,roomId);
    };
    @RequestMapping("findById")
    StudentBean findById(int id){
       return service.findById(id);
    }
    @RequestMapping("del")
    public void del(Integer id){
        service.del(id);
    };
}
